package com.hashbee.ctxinit;



import com.alibaba.druid.pool.DruidDataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;



import org.springframework.boot.context.properties.ConfigurationProperties;


import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.*;


import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;

@Configuration
public class MybatisCtxInit {

    private static  final Logger logger = LoggerFactory.getLogger(MybatisCtxInit.class);

    @Autowired
    private Environment env;



    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean(name = "dataSource")
    public DataSource dataSource(){

        DataSource dataSource=DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
        ((DruidDataSource) dataSource).setUrl(env.getProperty("spring.datasource.url"));
        ((DruidDataSource) dataSource).setUsername(env.getProperty("spring.datasource.username"));
        ((DruidDataSource) dataSource).setPassword(env.getProperty("spring.datasource.password"));
        ((DruidDataSource) dataSource).setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        return dataSource;
    }
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        sqlSessionFactoryBean.setTypeAliasesPackage("com.hashebee.**.domain");
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mybatis-mapping/**/*.xml"));
        sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sqlSessionFactoryBean.getObject();
    }
    /**
     * 配置事务管理器
     */
    @Bean
    @Qualifier("hashbeeTxMgr")
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        return new DataSourceTransactionManager(dataSource);
    }
}
